package com.whc.images.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.whc.images.domain.ResponseDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
public class IndexController {
    @Value("${storePath}")
    private String path;
    @Value("${password}")
    private String password;

    /**
     * 获取所有图片
     */
    @GetMapping("/list")
    public String imageList(){
        File dir = new File(path);
        String[] children = dir.list();
        if (children == null) {
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"目录不存在或它不是一个目录"));
        }
        List<String> names = new ArrayList<>(Arrays.asList(children));
        return JSONUtil.toJsonStr(new ResponseDto<>(names));
    }
    /**
     * 删除照片
     */
    @PostMapping("/delete")
    public String delete(@RequestParam("password")String password,@RequestParam("filename")String filename){
        if(null == password)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"password is required"));
        if(!password.equals(this.password))
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"wrong password"));
        File file = new File(path+filename);
        if(!file.exists())
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"image does not exist!"));
        if (file.delete()){
            System.out.println("图片："+filename+"\t删除成功");
            return JSONUtil.toJsonStr("delete successfully!");
        }
        return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"delete failed!"));
    }
    /**
     * 上传图片
     */
    @PostMapping(path = "/upload",consumes = "multipart/form-data")
    public String upload(String password, MultipartFile image){
        if(null == password)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"password is required"));
        if(null == image)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"image is required"));
        if(!password.equals(this.password))
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"wrong password"));
        //照片大小
        if(image.getSize()>10485760L)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"image oversize(10MB max!)"));
        String fileName = image.getOriginalFilename();
        if(null == fileName)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"image has no name"));
        String suffixName = fileName.substring(fileName.indexOf(".")).toLowerCase(Locale.ROOT);//后缀名
        if(!suffixName.equals(".png") && !suffixName.equals(".jpg")&&!suffixName.equals(".jpeg")&&!suffixName.equals(".gif")&&!suffixName.equals(".bmp"))
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"only .png .jpg .jpeg .gif .bmp supported!"));
        ///给图片改名
        fileName = UUID.randomUUID() + suffixName;
        File dest = new File(path + fileName);

        if(!dest.getParentFile().exists()){
            if(!dest.getParentFile().mkdirs())
                return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"parent dir created failed"));
        }
        try {
            image.transferTo(dest);
        }catch (IOException e){
            e.printStackTrace();
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"upload failed..."));
        }

        System.out.println("图片："+fileName+"\t上传成功");

        JSONObject rs = new JSONObject();
        rs.put("url",fileName);
        return JSONUtil.toJsonStr(new ResponseDto<>(rs));
    }

    /**
     * 用自定义图片名上传图片
     */
    @PostMapping(path = "/uploadWithName",consumes = "multipart/form-data")
    public String uploadWithName(String password,String imageName, MultipartFile image){
        if(null == password)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"password is required"));
        if(null == imageName)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"imageName is required"));
        if(null == image)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"image is required"));
        if(!password.equals(this.password))
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"wrong password"));
        //照片大小
        if(image.getSize()>10485760L)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"image oversize(10MB max!)"));
        String fileName = image.getOriginalFilename();
        if(null == fileName)
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"image has no name"));
        String suffixName = fileName.substring(fileName.indexOf(".")).toLowerCase(Locale.ROOT);//后缀名
        if(!suffixName.equals(".png") && !suffixName.equals(".jpg")&&!suffixName.equals(".jpeg")&&!suffixName.equals(".gif")&&!suffixName.equals(".bmp"))
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"only .png .jpg .jpeg supported!"));
        ///给图片改名
        fileName = imageName + ".jpg";//统一jpg格式
        File dest = new File(path + fileName);

        if(dest.exists())   dest.delete();
        if(!dest.getParentFile().exists()){
            if(!dest.getParentFile().mkdirs())
                return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"parent dir created failed"));
        }
        try {
            image.transferTo(dest);
        }catch (IOException e){
            e.printStackTrace();
            return JSONUtil.toJsonStr(new ResponseDto<>(false,400,"upload failed..."));
        }

        System.out.println("图片："+fileName+"\t上传成功");

        JSONObject rs = new JSONObject();
        rs.put("url",fileName);
        return JSONUtil.toJsonStr(new ResponseDto<>(rs));
    }
}
